uniform sampler2D suggestiveContourTexture, depthTexture;
uniform vec2 screenSize;
uniform bool useSmoothstep;
uniform float smoothstepStart, smoothstepEnd;
uniform vec4 color;
           
void main(void) { 
 
  float pixel;
  float depth;
  float minDepth= 1.0;
  float center= texture2D(suggestiveContourTexture, gl_FragCoord.xy/screenSize).x;
  float centerDepth= texture2D(depthTexture, gl_FragCoord.xy/screenSize).x;
  float max= 0.0;
  float darker= 0.0;
  float numPixels= 20.0; 
  int i;

  vec2 offsets[20];
  
  offsets[0]=   vec2(-2.0, -1.0);
  offsets[1]=   vec2(-2.0,  0.0);
  offsets[2]=   vec2(-2.0,  1.0);
  offsets[3]=   vec2(-1.0, -2.0);
  offsets[4]=   vec2(-1.0, -1.0);
  offsets[5]=   vec2(-1.0,  0.0);
  offsets[6]=   vec2(-1.0,  1.0);
  offsets[7]=   vec2(-1.0,  2.0);	
  offsets[8]=   vec2( 0.0, -2.0);
  offsets[9]=   vec2( 0.0, -1.0);
  offsets[10]=  vec2( 0.0,  1.0);
  offsets[11]=  vec2( 0.0,  2.0);
  offsets[12]=  vec2( 1.0, -2.0);
  offsets[13]=  vec2( 1.0, -1.0);
  offsets[14]=  vec2( 1.0,  0.0);
  offsets[15]=  vec2( 1.0,  1.0);
  offsets[16]=  vec2( 1.0,  2.0);
  offsets[17]=  vec2( 2.0, -1.0);
  offsets[18]=  vec2( 2.0,  0.0);
  offsets[19]=  vec2( 2.0,  1.0);


  for(i=0; i<10; i++){
      pixel = texture2D(suggestiveContourTexture, (gl_FragCoord.xy+offsets[i])/screenSize).x;
      depth= texture2D(depthTexture, (gl_FragCoord.xy+offsets[i])/screenSize).x;
      if(pixel<center) darker++;
      if(pixel>max) max= pixel;
      if(depth<minDepth) minDepth= depth;
  }
  for(i=10; i<20; i++){
      pixel = texture2D(suggestiveContourTexture, (gl_FragCoord.xy+offsets[i])/screenSize).x;		
      if(pixel<center) darker++;
      if(pixel>max) max= pixel;
      if(centerDepth==1.0){
        depth= texture2D(depthTexture, (gl_FragCoord.xy+offsets[i])/screenSize).x; 	
        if(depth<minDepth) minDepth= depth;
    }
  }


  float alpha= (1.0-(darker/numPixels))*(max-center)*color.a;  
  if(alpha!=0.0){
    if(useSmoothstep) alpha= smoothstep(smoothstepStart, smoothstepEnd, alpha);
    gl_FragColor= vec4(color.rgb, alpha);
    if(centerDepth==1.0) gl_FragDepth= minDepth;
    else gl_FragDepth= gl_FragCoord.z;	
  } 
  else{
    discard;
  }

  //gl_FragColor= texture2D(suggestiveContourTexture, (gl_FragCoord.xy)/screenSize);
}